import path from 'node:path';
import fs from 'fs-extra';
import { WxScript, WxStyle, WxTemplate } from ".";
import util, { dom, LogType, log } from "../util";


export class WxFile {
    template: WxTemplate;
    script: WxScript;
    style: WxStyle;
    source: string;

    constructor(public src: string, public dest: string, public isApp?: Boolean | undefined) {
        this.source = util.readFile(src);
        let {
            script: { code: scriptCode },
            template: { code: templateCode },
            style: { code: styleCode }
        } = dom.getSFC(this.source);

        this.template = new WxTemplate(templateCode, isApp);
        this.script = new WxScript(scriptCode, isApp);
        this.style = new WxStyle(styleCode, isApp);
    }

    get config() {
        return this.script.config;
    }

    async writeFile(relativePath: string) {
        try {
            let templateCode = await this.template.generator();
            let scriptCode = await this.script.generator();
            let styleCode = await this.style.generator();
            let code = dom.combineCode(templateCode, scriptCode, styleCode);
            util.writeFile(this.dest, code);
            log.msg(LogType.WRITE, `${relativePath}`);
            this.copyImages(relativePath);
        }
        catch (err) {
            log.error(`写入${relativePath}失败，${err}`);
        }
    }

    copyImages(relativePath: string) {
        const srcDir = path.join(path.dirname(this.src), 'images');
        const destDir = path.join(path.dirname(this.dest), 'images');
        try {
            if (fs.existsSync(srcDir) && (this.isApp || !fs.existsSync(destDir))) {
                const relativeDir = path.join(path.dirname(relativePath), 'images');
                fs.copySync(srcDir, destDir);
                log.msg(LogType.COPY, `${relativeDir}目录`);
            }
        }
        catch (e) {
            log.error(`拷贝${srcDir}失败，${e}`);
        }
    }
}
